<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="paperName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入试卷名称"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="考试班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable filterable>
          <el-option
            v-for="item in gradeOptions"
            :key="item.classId"
            :label="item.className"
            :value="item.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddAuto"
          v-hasPermi="['manage:paper:add']"
        >自动组卷</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Plus"
          @click="handleAddManual"
          v-hasPermi="['manage:paper:add']"
        >手动组卷</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Plus"
          @click="handleAddWrong"
          v-hasPermi="['manage:paper:add']"
        >错题组卷</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:paper:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="试卷名称" align="center" prop="paperName" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="考试班级" align="center" prop="className" width="150" />
      <el-table-column label="考试时长" align="center" prop="duration" width="100">
        <template #default="scope">
          <span class="duration-tag">{{ scope.row.duration }} 分钟</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template #default="scope">
          <span class="time-tag">{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="160">
        <template #default="scope">
          <span class="time-tag">{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="题目数量" align="center" prop="number" width="100">
        <template #default="scope">
          <span class="count-tag">{{ scope.row.number || 0 }} 题</span>
        </template>
      </el-table-column>
      <el-table-column label="总分" align="center" prop="totalScore" width="80">
        <template #default="scope">
          <span class="score-tag">{{ scope.row.totalScore || calculateTotalScore(scope.row) }}分</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row)">
            {{ getStatusText(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="160" /> -->
      <el-table-column label="操作" align="center" width="280">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handlePreview(scope.row)">预览</el-button>
          <el-button 
            link 
            type="success" 
            icon="Check" 
            v-if="scope.row.status === 0" 
            @click="handlePublish(scope.row)"
            v-hasPermi="['manage:paper:edit']"
          >发布</el-button>
          <el-button 
            link 
            type="warning" 
            icon="Close" 
            v-if="scope.row.status === 1" 
            @click="handleUnpublish(scope.row)"
            v-hasPermi="['manage:paper:edit']"
          >下架</el-button>
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            v-if="scope.row.status !== 1" 
            @click="handleEdit(scope.row)"
            v-hasPermi="['manage:paper:edit']"
          >修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:paper:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
   
    <!-- 预览试卷对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="试卷预览"
      width="80%"
      append-to-body
      @opened="renderMathInPreview" 
    >
      <div ref="previewContainer" class="paper-preview-container">
        <!-- 试卷头部信息 -->
        <div class="paper-header">
          <h1>{{ previewPaper.paperName }}</h1>
          <div class="paper-info">
            <p><strong>考试班级：</strong>{{ previewPaper.className }}</p>
            <p><strong>考试时长：</strong>{{ previewPaper.duration }} 分钟</p>
            <p><strong>开始时间：</strong>{{ previewPaper.startTime }}</p>
            <p><strong>结束时间：</strong>{{ previewPaper.endTime }}</p>
            <p><strong>总分：</strong>{{ previewPaper.totalScore || calculateTotalScore(previewPaper) }} 分</p>
          </div>
        </div>

        <!-- 试卷内容 -->
        <div class="paper-content" v-loading="previewLoading">
          <!-- 计算题型顺序的变量 -->
          <div v-if="previewPaper.questions" style="display: none;">
            {{ sectionIndex = 0 }}
          </div>
          
          <!-- 单选题部分 -->
          <div v-if="previewPaper.singleChoiceQuestions && previewPaper.singleChoiceQuestions.length > 0" class="question-section">
            <h2>{{ getSectionNumber(sectionIndex++) }}、单选题（共{{ previewPaper.singleChoiceQuestions.length }}题，
              {{ getPartScore('singleChoice', previewPaper) }}分）</h2>
            <div v-for="(item, index) in previewPaper.singleChoiceQuestions" :key="'single-'+item.questionId" 
              class="question-item">
              <div class="question-title">
                {{ index + 1 }}. <span class="question-score">({{ getQuestionScore(item.question, 'singleChoice', previewPaper) }}分)</span> 
                <span v-html="renderMathContent(item.question.questionContent)"></span>
              </div>
              <div v-if="item.question.options && item.question.options.length > 0" class="question-options">
                <div v-for="option in item.question.options" :key="option.optionId" class="question-option">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <span class="option-content" v-html="renderMathContent(option.optionContent)"></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 多选题部分 -->
          <div v-if="previewPaper.multiChoiceQuestions && previewPaper.multiChoiceQuestions.length > 0" class="question-section">
            <h2>{{ getSectionNumber(sectionIndex++) }}、多选题（共{{ previewPaper.multiChoiceQuestions.length }}题，
              {{ getPartScore('multiChoice', previewPaper) }}分）</h2>
            <div v-for="(item, index) in previewPaper.multiChoiceQuestions" :key="'multi-'+item.questionId" 
              class="question-item">
              <div class="question-title">
                {{ index + 1 }}. <span class="question-score">({{ getQuestionScore(item.question, 'multiChoice', previewPaper) }}分)</span> 
                <span v-html="renderMathContent(item.question.questionContent)"></span>
              </div>
              <div v-if="item.question.options && item.question.options.length > 0" class="question-options">
                <div v-for="option in item.question.options" :key="option.optionId" class="question-option">
                  <span class="option-label">{{ option.optionLabel }}.</span>
                  <span class="option-content" v-html="renderMathContent(option.optionContent)"></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 判断题部分 -->
          <div v-if="previewPaper.judgmentQuestions && previewPaper.judgmentQuestions.length > 0" class="question-section">
            <h2>{{ getSectionNumber(sectionIndex++) }}、判断题（共{{ previewPaper.judgmentQuestions.length }}题，
              {{ getPartScore('judgment', previewPaper) }}分）</h2>
            <div v-for="(item, index) in previewPaper.judgmentQuestions" :key="'judgment-'+item.questionId" 
              class="question-item">
              <div class="question-title">
                {{ index + 1 }}. <span class="question-score">({{ getQuestionScore(item.question, 'judgment', previewPaper) }}分)</span> 
                <span v-html="renderMathContent(item.question.questionContent)"></span>
              </div>
              <div class="question-options">
                <div class="question-option">
                  <span class="option-label">A.</span>
                  <span class="option-content">正确</span>
                </div>
                <div class="question-option">
                  <span class="option-label">B.</span>
                  <span class="option-content">错误</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 填空题部分 -->
          <div v-if="previewPaper.fillBlankQuestions && previewPaper.fillBlankQuestions.length > 0" class="question-section">
            <h2>{{ getSectionNumber(sectionIndex++) }}、填空题（共{{ previewPaper.fillBlankQuestions.length }}题，
              {{ getPartScore('fillBlank', previewPaper) }}分）</h2>
            <div v-for="(item, index) in previewPaper.fillBlankQuestions" :key="'fillBlank-'+item.questionId" 
              class="question-item">
              <div class="question-title">
                {{ index + 1 }}. <span class="question-score">({{ getQuestionScore(item.question, 'fillBlank', previewPaper) }}分)</span> 
                <span v-html="renderMathContent(renderFillBlankQuestion(item.question.questionContent))"></span>
              </div>
            </div>
          </div>

          <!-- 简答题部分 -->
          <div v-if="previewPaper.essayQuestions && previewPaper.essayQuestions.length > 0" class="question-section">
            <h2>{{ getSectionNumber(sectionIndex++) }}、简答题（共{{ previewPaper.essayQuestions.length }}题，
              {{ getPartScore('essay', previewPaper) }}分）</h2>
            <div v-for="(item, index) in previewPaper.essayQuestions" :key="'essay-'+item.questionId" 
              class="question-item">
              <div class="question-title">
                {{ index + 1 }}. <span class="question-score">({{ getQuestionScore(item.question, 'essay', previewPaper) }}分)</span> 
                <span v-html="renderMathContent(item.question.questionContent)"></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Paper">
import { listPaper, getPaper, delPaper, publishPaper, unpublishPaper } from "@/api/manage/paper";
import { getQuestion } from "@/api/manage/question";
import { listGrade, getMyClasses } from "@/api/manage/grade";
import { getCurrentInstance, ref, reactive, toRefs, onMounted, watch, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import useUserStore from '@/store/modules/user';
import katex from 'katex';
import 'katex/dist/katex.min.css';
import { ElMessage } from 'element-plus';

const router = useRouter();
const { proxy } = getCurrentInstance();
const userStore = useUserStore();

// 试卷列表数据
const paperList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 班级数据
const gradeOptions = ref([]);

// 预览相关
const previewVisible = ref(false);
const previewPaper = ref({});
const previewContainer = ref(null);
const previewLoading = ref(false);
let sectionIndex = 0; // 定义sectionIndex变量用于计算题型序号

// 状态选项
const statusOptions = [
  { value: 0, label: '草稿' },
  { value: 1, label: '已发布' },
  { value: 2, label: '已结束' }
];

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    paperName: '',
    classId: null,
    status: null
  }
});

const { queryParams } = toRefs(data);

// 添加数学公式渲染函数
function renderMathContent(content) {
  if (!content) return '';
  
  try {
    // 处理块级公式 $$...$$
    content = content.replace(/\$\$([\s\S]+?)\$\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          displayMode: true,
          throwOnError: false
        });
      } catch (err) {
        console.error('KaTeX error:', err);
        return match;
      }
    });

    // 处理行内公式 $...$
    content = content.replace(/\$([^\$]+)\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          displayMode: false,
          throwOnError: false
        });
      } catch (err) {
        console.error('KaTeX error:', err);
        return match;
      }
    });

    return content;
  } catch (err) {
    console.error('Content processing error:', err);
    return content;
  }
}

watch(
  () => router.currentRoute.value.path,
  () => {
    getList();
  }
);

/** 查询试卷列表 */
function getList() {
  loading.value = true;
  
  // 获取当前用户信息
  userStore.getInfo().then(res => {
    // 检查是否为教师角色
    const isTeacher = res.roles && res.roles.includes('teacher');
    
    if (isTeacher) {
      // 如果是教师，只获取该教师任课班级的试卷
      getMyClasses().then(response => {
        const teacherClassIds = response.data.map(item => item.classId);
        
        // 如果有指定班级且在教师的班级范围内
        if (queryParams.value.classId && teacherClassIds.includes(queryParams.value.classId)) {
          // 使用选定的班级ID
          listPaper(queryParams.value).then(response => {
            paperList.value = response.rows;
            total.value = response.total;
            loading.value = false;
          });
        } else if (teacherClassIds.length > 0) {
          // 使用教师所有班级的ID集合
          const params = { ...queryParams.value, classIds: teacherClassIds.join(',') };
          listPaper(params).then(response => {
            paperList.value = response.rows;
            total.value = response.total;
            loading.value = false;
          });
        } else {
          // 教师没有班级，返回空列表
          paperList.value = [];
          total.value = 0;
          loading.value = false;
        }
      });
    } else {
      // 如果是管理员，获取所有试卷
      listPaper(queryParams.value).then(response => {
        paperList.value = response.rows;
        total.value = response.total;
        loading.value = false;
      });
    }
  }).catch(error => {
    console.error("获取用户信息失败", error);
    loading.value = false;
  });
}

/** 获取班级列表 */
function getGradeList() {
  // 获取当前用户信息
  userStore.getInfo().then(res => {
    // 检查是否为教师角色
    const isTeacher = res.roles && res.roles.includes('teacher');
    
    if (isTeacher) {
      // 如果是教师，只获取该教师任课的班级
      getMyClasses().then(response => {
        gradeOptions.value = response.data || [];
      });
    } else {
      // 如果是管理员，获取所有班级
      listGrade().then(response => {
        gradeOptions.value = response.rows || [];
      });
    }
  });
}

/** 获取试卷题目数量 */
function getQuestionCount(paper) {
  // 首先检查paper.questions是否存在
  if (paper.questions && paper.questions.length > 0) {
    return paper.questions.length;
  }
  
  // 如果没有questions属性，尝试使用各题型数量
  const singleChoiceCount = paper.singleChoiceCount || 0;
  const multiChoiceCount = paper.multiChoiceCount || 0;
  const judgmentCount = paper.judgmentCount || 0;
  const fillBlankCount = paper.fillBlankCount || 0;
  const essayCount = paper.essayCount || 0;
  
  return singleChoiceCount + multiChoiceCount + judgmentCount + fillBlankCount + essayCount;
}

/** 计算试卷总分 */
function calculateTotalScore(paper) {
  let totalScore = 0;
  
  // 计算各题型总分
  if (paper.useOriginalScore) {
    // 如果使用原始分数，从各题目中累加
    if (paper.singleChoiceQuestions) {
      totalScore += paper.singleChoiceQuestions.reduce((sum, q) => sum + (q.question ? parseFloat(q.question.score) : (q.questionScore ? parseFloat(q.questionScore) : 0)), 0);
    }
    if (paper.multiChoiceQuestions) {
      totalScore += paper.multiChoiceQuestions.reduce((sum, q) => sum + (q.question ? parseFloat(q.question.score) : (q.questionScore ? parseFloat(q.questionScore) : 0)), 0);
    }
    if (paper.judgmentQuestions) {
      totalScore += paper.judgmentQuestions.reduce((sum, q) => sum + (q.question ? parseFloat(q.question.score) : (q.questionScore ? parseFloat(q.questionScore) : 0)), 0);
    }
    if (paper.fillBlankQuestions) {
      totalScore += paper.fillBlankQuestions.reduce((sum, q) => sum + (q.question ? parseFloat(q.question.score) : (q.questionScore ? parseFloat(q.questionScore) : 0)), 0);
    }
    if (paper.essayQuestions) {
      totalScore += paper.essayQuestions.reduce((sum, q) => sum + (q.question ? parseFloat(q.question.score) : (q.questionScore ? parseFloat(q.questionScore) : 0)), 0);
    }
    
    // 如果使用questions数组
    if (paper.questions && paper.questions.length > 0) {
      // 如果之前未计算出分数，则从questions计算
      if (totalScore === 0) {
        totalScore = paper.questions.reduce((sum, q) => sum + (q.questionScore ? parseFloat(q.questionScore) : 0), 0);
      }
    }
  } else {
    // 如果使用统一分数
    totalScore += (paper.singleChoiceCount || 0) * (paper.singleChoiceScore || 0);
    totalScore += (paper.multiChoiceCount || 0) * (paper.multiChoiceScore || 0);
    totalScore += (paper.judgmentCount || 0) * (paper.judgmentScore || 0);
    totalScore += (paper.fillBlankCount || 0) * (paper.fillBlankScore || 0);
    totalScore += (paper.essayCount || 0) * (paper.essayScore || 0);
    
    // 如果使用questions数组但没有分类
    if (paper.questions && paper.questions.length > 0 && totalScore === 0) {
      // 按题型统计数量和分数
      const types = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0};
      const scores = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0};
      
      paper.questions.forEach(q => {
        if (q.question && q.questionScore) {
          const type = q.question.questionType;
          types[type] = (types[type] || 0) + 1;
          scores[type] = parseFloat(q.questionScore);
        }
      });
      
      totalScore += types[0] * scores[0];
      totalScore += types[1] * scores[1];
      totalScore += types[2] * scores[2];
      totalScore += types[3] * scores[3];
      totalScore += types[4] * scores[4];
    }
  }
  
  return totalScore.toFixed(2);
}

/** 获取某类题目总分 */
function getPartScore(type, paper) {
  let score = 0;
  
  // 定义各题型对应的字段名
  const keyMap = {
    singleChoice: {
      questions: 'singleChoiceQuestions',
      count: 'singleChoiceCount',
      score: 'singleChoiceScore'
    },
    multiChoice: {
      questions: 'multiChoiceQuestions',
      count: 'multiChoiceCount',
      score: 'multiChoiceScore'
    },
    judgment: {
      questions: 'judgmentQuestions',
      count: 'judgmentCount',
      score: 'judgmentScore'
    },
    fillBlank: {
      questions: 'fillBlankQuestions',
      count: 'fillBlankCount',
      score: 'fillBlankScore'
    },
    essay: {
      questions: 'essayQuestions',
      count: 'essayCount',
      score: 'essayScore'
    }
  };
  
  const keys = keyMap[type];
  if (!keys) return "0.00";
  
  // 优先从问题列表中获取分数（这些是从tgs_paper_question表中获取的实际分数）
  if (paper[keys.questions] && paper[keys.questions].length > 0) {
    score = paper[keys.questions].reduce((sum, q) => {
      // 优先从paperQuestion对象的questionScore字段获取分数
      // 这是tgs_paper_question表中存储的实际分数
      let questionScore = 0;
      
      if (q.questionScore) {
        // 直接从paperQuestion对象中获取分数
        questionScore = parseFloat(q.questionScore);
      } else if (q.question && q.question.score) {
        // 如果没有questionScore但有question对象，从question对象获取分数
        questionScore = parseFloat(q.question.score);
      }
      
      // 确保分数是合法的数字
      questionScore = isNaN(questionScore) ? 0 : questionScore;
      
      return sum + questionScore;
    }, 0);
  } else if (paper[keys.count] && paper[keys.score]) {
    // 如果没有问题列表但有数量和分数，使用它们计算
    // 这种情况适用于自动组卷或尚未保存的试卷
    score = parseFloat(paper[keys.count]) * parseFloat(paper[keys.score]);
  }
  
  return score.toFixed(2);
}

/** 获取单个题目分数 */
function getQuestionScore(question, type, paper) {
  if (!question) return "0.00";
  
  // 如果试卷使用统一设置分数（而不是原有分数）
  if (paper && paper.useOriginalScore === false) {
    // 计算该题型的平均分（总分除以题目数）
    const typeMap = {
      'singleChoice': { questions: 'singleChoiceQuestions', count: 'singleChoiceCount' },
      'multiChoice': { questions: 'multiChoiceQuestions', count: 'multiChoiceCount' },
      'judgment': { questions: 'judgmentQuestions', count: 'judgmentCount' },
      'fillBlank': { questions: 'fillBlankQuestions', count: 'fillBlankCount' },
      'essay': { questions: 'essayQuestions', count: 'essayCount' }
    };
    
    const typeInfo = typeMap[type];
    if (typeInfo) {
      // 优先使用题目列表长度
      const questionsCount = paper[typeInfo.questions] ? paper[typeInfo.questions].length : 
                             (paper[typeInfo.count] || 0);
      
      // 如果有题目，则计算该题型的平均分
      if (questionsCount > 0) {
        // 获取该题型总分
        const totalTypeScore = parseFloat(getPartScore(type, paper));
        // 计算平均分
        const averageScore = totalTypeScore / questionsCount;
        return averageScore.toFixed(2);
      }
    }
    
    // 如果无法按题型计算，则尝试使用统一设置的分数
    const scoreMap = {
      'singleChoice': 'singleChoiceScore',
      'multiChoice': 'multiChoiceScore',
      'judgment': 'judgmentScore',
      'fillBlank': 'fillBlankScore',
      'essay': 'essayScore'
    };
    
    if (paper[scoreMap[type]]) {
      const score = parseFloat(paper[scoreMap[type]]);
      return isNaN(score) ? "0.00" : score.toFixed(2);
    }
    
    return "0.00";
  }
  
  // 如果试卷使用原有分数，则按原逻辑处理
  
  // 优先处理PaperQuestion对象
  // 使用questionScore字段，这是tgs_paper_question表中存储的实际分数
  if (question.questionScore) {
    const score = parseFloat(question.questionScore);
    return isNaN(score) ? "0.00" : score.toFixed(2);
  }
  
  // 如果没有questionScore但有question对象
  if (question.question && question.question.score) {
    const score = parseFloat(question.question.score);
    return isNaN(score) ? "0.00" : score.toFixed(2);
  }
  
  // 如果是直接的question对象
  if (question.score) {
    const score = parseFloat(question.score);
    return isNaN(score) ? "0.00" : score.toFixed(2);
  }
  
  // 如果所有方法都失败，返回0
  return "0.00";
}

/** 渲染填空题内容 */
function renderFillBlankQuestion(content) {
  if (!content) return '';
  
  // 将三个或更多下划线替换为空白行
  return content.replace(/_{3,}/g, '<span class="blank-line">_________</span>');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.paperId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 自动组卷按钮操作 */
function handleAddAuto() {
  router.push('/paper/auto');
}

/** 手动组卷按钮操作 */
function handleAddManual() {
  router.push('/paper/manual');
}

/** 错题组卷按钮操作 */
function handleAddWrong() {
  router.push('/paper/wrong');
}

/** 预览按钮操作 */
function handlePreview(row) {
  previewLoading.value = true;
  loading.value = true;
  getPaper(row.paperId).then(async response => {
    previewPaper.value = response.data;
    
    // 整理数据，将题目分类
    if (previewPaper.value.questions && previewPaper.value.questions.length > 0) {
      // 按题型分类并排序
      previewPaper.value.singleChoiceQuestions = previewPaper.value.questions
        .filter(q => q.question && q.question.questionType === 0)
        .sort((a, b) => a.questionOrder - b.questionOrder);
        
      previewPaper.value.multiChoiceQuestions = previewPaper.value.questions
        .filter(q => q.question && q.question.questionType === 1)
        .sort((a, b) => a.questionOrder - b.questionOrder);
        
      previewPaper.value.judgmentQuestions = previewPaper.value.questions
        .filter(q => q.question && q.question.questionType === 2)
        .sort((a, b) => a.questionOrder - b.questionOrder);
        
      previewPaper.value.fillBlankQuestions = previewPaper.value.questions
        .filter(q => q.question && q.question.questionType === 3)
        .sort((a, b) => a.questionOrder - b.questionOrder);
        
      previewPaper.value.essayQuestions = previewPaper.value.questions
        .filter(q => q.question && q.question.questionType === 4)
        .sort((a, b) => a.questionOrder - b.questionOrder);
      
      // 更新各题型数量属性以便计算分数
      previewPaper.value.singleChoiceCount = previewPaper.value.singleChoiceQuestions.length;
      previewPaper.value.multiChoiceCount = previewPaper.value.multiChoiceQuestions.length;
      previewPaper.value.judgmentCount = previewPaper.value.judgmentQuestions.length;
      previewPaper.value.fillBlankCount = previewPaper.value.fillBlankQuestions.length;
      previewPaper.value.essayCount = previewPaper.value.essayQuestions.length;
    
      // 加载单选题和多选题的选项
      try {
        // 单选题选项加载
        for (const item of previewPaper.value.singleChoiceQuestions) {
          if (item.question && (!item.question.options || item.question.options.length === 0)) {
            try {
              const { data } = await getQuestion(item.question.questionId);
              if (data && data.options) {
                item.question.options = data.options;
              }
            } catch (error) {
              console.error(`加载单选题${item.question.questionId}选项失败:`, error);
            }
          }
        }

        // 多选题选项加载
        for (const item of previewPaper.value.multiChoiceQuestions) {
          if (item.question && (!item.question.options || item.question.options.length === 0)) {
            try {
              const { data } = await getQuestion(item.question.questionId);
              if (data && data.options) {
                item.question.options = data.options;
              }
            } catch (error) {
              console.error(`加载多选题${item.question.questionId}选项失败:`, error);
            }
          }
        }
      } catch (error) {
        console.error('加载题目选项时出错:', error);
        ElMessage.warning('部分题目选项加载失败，预览可能不完整');
      }
    }
    
    loading.value = false;
    previewVisible.value = true;
    previewLoading.value = false;
  }).catch(error => {
    loading.value = false;
    previewLoading.value = false;
    console.error('获取试卷详情失败:', error);
    ElMessage.error('获取试卷详情失败');
  });
}

/** 发布按钮操作 */
function handlePublish(row) {
  const paperId = row.paperId;
  proxy.$modal.confirm('确认要发布该试卷吗？发布后学生将可以参加考试。').then(function() {
    return publishPaper(paperId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("发布成功");
  }).catch(() => {});
}

/** 下架按钮操作 */
function handleUnpublish(row) {
  const paperId = row.paperId;
  proxy.$modal.confirm('确认要下架该试卷吗？下架后学生将无法参加该考试。').then(function() {
    return unpublishPaper(paperId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("下架成功");
  }).catch(() => {});
}

/** 删除按钮操作 */
function handleDelete(row) {
  const paperIds = row.paperId || ids.value;
  
  // 检查是否为已发布状态
  if (row.status === 1) {
    proxy.$modal.msgError("试卷已发布，无法删除，请先下架后再删除");
    return;
  }
  
  // 如果是批量删除，需要检查选中的试卷中是否有已发布的
  if (!row.paperId && ids.value.length > 0) {
    const publishedPaper = paperList.value.find(p => ids.value.includes(p.paperId) && p.status === 1);
    if (publishedPaper) {
      proxy.$modal.msgError(`包含已发布状态的试卷【${publishedPaper.paperName}】，无法删除`);
      return;
    }
  }
  
  proxy.$modal.confirm('确认要删除选中的试卷吗？删除后将无法恢复。').then(function() {
    return delPaper(paperIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch((error) => {
    if (error && error.response && error.response.data && error.response.data.msg) {
      proxy.$modal.msgError(error.response.data.msg);
    }
  });
}

/** 获取状态颜色类型 */
function getStatusType(paper) {
  // 检查是否已过期
  if (paper.status === 2) {
    return 'danger'; // 结束状态改为红色 danger
  } else if (paper.status === 1) {
    // 检查当前时间是否超过结束时间
    const now = new Date();
    const endTime = new Date(paper.endTime);
    if (now > endTime) {
      return 'danger'; // 已过期但状态未更新也改为红色 danger
    }
    return 'success'; // 发布状态
  } else {
    return 'warning'; // 草稿状态
  }
}

/** 获取状态文本 */
function getStatusText(paper) {
  // 检查是否已过期
  if (paper.status === 2) {
    return '已结束';
  } else if (paper.status === 1) {
    // 检查当前时间是否超过结束时间
    const now = new Date();
    const endTime = new Date(paper.endTime);
    if (now > endTime) {
      return '已过期';
    }
    return '已发布';
  } else {
    return '草稿';
  }
}

/** 修改按钮操作 */
function handleEdit(row) {
  router.push({ 
    path: '/paper/manual/edit', 
    query: { paperId: row.paperId } 
  });
}

/** 修改MathJax加载方式 */
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      // 如果已经加载，重新配置并尝试渲染
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
    // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
    };
    document.head.appendChild(script);
  });
};

/** 优化渲染函数，添加更多日志和重试机制 */
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    
    // 备选方案：使用KaTeX
    try {
      if (previewContainer.value) {
        // 找到所有包含数学公式的元素
        const elements = previewContainer.value.querySelectorAll('.question-title, .question-options, .option-content');
        elements.forEach(el => {
          const html = el.innerHTML;
          if (html && (html.includes('$') || html.includes('\\('))) {
            // 重新渲染数学公式
            el.innerHTML = renderMathContent(html);
          }
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

// 获取题型的编号(一、二、三、四、五)
function getSectionNumber(index) {
  const chineseNumbers = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
  return chineseNumbers[index] || (index + 1);
}

// 页面加载时获取数据
onMounted(() => {
  getList();
  getGradeList();
});
</script>

<style scoped>

:deep(.el-tag) {
  margin-right: 5px;
}

/* 预览试卷样式 */
.paper-preview-container {
  padding: 20px;
}

.paper-header {
  text-align: center;
  margin-bottom: 30px;
}

.paper-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 15px;
}

.paper-info {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
}

.paper-content {
  font-size: 15px;
  line-height: 1.8;
}

.question-section {
  margin-bottom: 40px;
}

.question-section h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.question-item {
  margin-bottom: 25px;
}

.question-title {
  margin-bottom: 10px;
  font-weight: 500;
}

.question-score {
  color: #409EFF;
  font-weight: bold;
  margin-right: 5px;
}

.question-options {
  padding-left: 20px;
}

.question-option {
  margin-bottom: 8px;
  display: flex;
}

.option-label {
  width: 30px;
  font-weight: bold;
}

.option-content {
  flex: 1;
}

.blank-line {
  display: inline-block;
  min-width: 150px;
  border-bottom: 1px solid #000;
  margin: 0 5px;
}

.essay-answer-area {
  margin-top: 15px;
}

.essay-lines {
  min-height: 150px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: linear-gradient(#fff, #fff 19px, #ddd 19px, #ddd 20px);
  background-size: 100% 20px;
  margin-top: 10px;
}

/* KaTeX 相关样式 */
:deep(.katex) {
  font-size: 1.1em;
}

:deep(.katex-display) {
  margin: 1em 0;
  overflow-x: auto;
  overflow-y: hidden;
}

:deep(.katex-html) {
  max-width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}

.time-tag {
  color: #85ce61;
  font-weight: bold;
  display: inline-block;
  padding: 2px 6px;
  background-color: #f0f9eb;
  border-radius: 4px;
  border: 1px solid #85ce61;
  font-size: 12px;
}

.count-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #f0f2f5;
  border: 1px solid #909399;
  border-radius: 4px;
  color: #606266;
  font-weight: bold;
  font-size: 12px;
}

.score-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-weight: bold;
  font-size: 12px;
}
.duration-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #eee5f9;
  border: 1px solid #7d21ee;
  border-radius: 4px;
  color: #7d21ee;
  font-weight: bold;
  font-size: 12px;
}
</style>